package com.riddle.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import com.riddle.model.Article;
import com.riddle.model.Category;
import com.riddle.util.StringUtil;

@Repository
@Scope("prototype")
public class ArticleDao extends BaseDao<Article> {

	@Override
	public Article query(Long id) {
		return super.query(id, "selectArticleById");
	}

	@Override
	public List<Article> queryModelByPage(Integer page, Integer rows, String query) {
		// TODO Auto-generated method stub
		return super.queryModelByPage(page, rows, query, "selectArticleForQuery");
	}

	@Override
	public void insert(Article model) {
		super.insert(model, "insertArticle");
	}

	@Override
	public void update(Article model) {
		// TODO Auto-generated method stub
		super.update(model, "updatetArticle");
	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub
		super.delete(id, "deleteArticle");
	}

	@Override
	public List<Article> queryParent() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public List<Article> getArticles(){
		return super.query("selectArticles");
	}
	
	public List<Article> getRecentArticles(){
		return super.query("selectRecentArticles");
	}
	
	public List<Category> getCategories(String query){
		Map param = new HashMap<String, String>();
		if(!StringUtil.isNullOrEmpty(query)) {
			param.put("query", query);
		}
		try(SqlSession session = openSession()){
			return session.selectList("selectCategory", param);
		}
	}

	public List<Category> getCategoriesWithCount(){
		try(SqlSession session = openSession()){
			return session.selectList("selectCategoryWithCount");
		}
	}
	
	public Category getCategoryWithArticles(Long id) {
		Map param = new HashMap<String, Long>();
		if(id != null) {
			param.put("id", id);
		}
		try(SqlSession session = openSession()){
			return session.selectOne("selectCategoryWithArticles", param);
		}
	}
}
